package com.appleyk.sso.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * <p>越努力，越幸运</p>
 *
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  8:27 下午 2021/1/4
 */
@RestController
@CrossOrigin
@RequestMapping(value = "auth",produces = {"text/plain;charset=utf-8"})
public class LoginController {

    @PostMapping("/login-success")
    public String loginSuccess(){
        return getUserName()+",登录成功!";
    }

    @PostMapping("/login-failure")
    public String loginFail(){
        return "登录失败!";
    }

    @GetMapping("/logout")
    public String loginOut(){
        return "退出成功!";
    }

    @GetMapping("/hello")
    public String hello(){
        return getUserName()+",你好!";
    }

    // 访问资源r1
    @GetMapping("/r/r1")
    public String getResource1(){
        return getUserName()+",访问资源1";
    }

    // 访问资源r2
    @GetMapping("/r/r2")
    public String getResource2(){
        return getUserName()+",访问资源2";
    }

    // 访问资源r3
    @GetMapping("/r/r3")
    // 只有有p1和p3中的任意一个权限既可以访问该资源
    @PreAuthorize("hasAnyAuthority('p1','p3')")
    public String getResource3(){
        return getUserName()+",访问资源3";
    }

    // 访问资源r4
    @GetMapping("/r/r4")
    // 只要具有p4权限才可以访问该资源
    @PreAuthorize("hasAuthority('p4')")
    public String getResource4(){
        return getUserName()+",访问资源4";
    }


    // 通过SecurityContext上下文来获取用户信息
    private String getUserName(){
        String userName = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal == null){
            userName = "匿名";
        }
        if (principal instanceof UserDetails){
            System.out.println("UserDetails");
            userName = ((UserDetails) principal).getUsername();
        }else{
            userName = principal.toString();
        }
        return userName;
    }
}
